package zhan;

import java.util.Iterator;

/**
 * @Author: Hasee
 * @Date: 2020-12-03 09:32:12
 */
public class Stack<T> implements Iterable<T> {
    // 头结点
    private Node head;
    //记录元素个数
    private int N;

    //构造函数
    public Stack(){
        head=new Node(null,null);
        N=0;
    }

    //判断元素个数是否为空
    public boolean isEmpty(){
        return N==0;

    }
    public T firstValue(){
        return (T) head.next.item;
    }
    //把t元素压栈
    public void push(T t){
        Node oldFirstNode=head.next;
        Node newNode=new Node(t,null);
        head.next=newNode;
        newNode.next=oldFirstNode;
        N++;
    }

    public T pop(){
        Node oldFirstNode=head.next;
        if (oldFirstNode==null){
            return null;
        }
        head.next=head.next.next;

        N--;
        return (T) oldFirstNode.item;
    }

    @Override
    public Iterator<T> iterator() {
        return new SIterator();
    }

//    @Override
//    public Iterator iterator() {
//        return new SIterator();
//    }

    public class SIterator implements Iterator<T>{
        private  Node n =head;

        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public T next() {
            Node node=n.next;
            n=n.next;
            return (T)node.item;
        }
    }
}
